package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.im.util.IMConfig;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisKeys;
import com.glela.common.util.JsonUtil;
import com.glela.live.mapper.LiveOrderMapper;
import com.glela.live.messages.StreamMessage;
import com.glela.live.messages.User;
import com.glela.live.model.PublishHistory;
import com.glela.live.models.ChatRoomInfo;
import com.glela.live.service.ChatRoomService;
import com.glela.live.service.LivePlanService;
import com.glela.live.service.LiveRecordService;
import com.glela.live.service.PublishHistoryService;
import com.glela.live.util.RongCloud;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/publish")
public class PublishHistoryController extends LiveBaseController{

    @Autowired
    private PublishHistoryService publishHistoryService;

    @Autowired
    private LivePlanService livePlanService;

    @Autowired
    private LiveRecordService liveRecordService;

    @Autowired
    private ChatRoomService chatRoomService;

    @Autowired
    private LiveOrderMapper liveOrderMapper;

    @RequestMapping("/addPublishHistory")
    public String addPublishHistory(HttpServletRequest request){
        if (StringUtils.isNotBlank(redisUtil.get(RedisKey.REDIS_KEY_PUBLISH_KEY+request.getParameter("id")))){
            return "ok";
        }
        PublishHistory requestVo = new PublishHistory();
        requestVo.setLivePlanId(Integer.valueOf(request.getParameter("id")));
        redisUtil.set(RedisKey.REDIS_KEY_PUBLISH_KEY+request.getParameter("id"),"1",5);
        requestVo.setPushPullUrl(request.getParameter("app"));
        requestVo.setCallbackTime(Long.valueOf(request.getParameter("time")));
        requestVo.setAction(request.getParameter("action"));
        requestVo.setAppName(request.getParameter("appname"));
        requestVo.setNode(request.getParameter("node"));
        requestVo.setIp(request.getParameter("ip"));
        requestVo.setUsrargs(request.getParameter("usrargs"));
/*        if ("publish".equals(requestVo.getAction())){
            *//*LiveRecord liveRecord = new LiveRecord();
            liveRecord.setId(System.currentTimeMillis()+requestVo.getStreamName());
            liveRecord.setLiveUserId(Long.valueOf(requestVo.getStreamName()));
            liveRecordService.add(liveRecord);*//*
            //开始时间在liveplan时间之后且是直播状态或是开始时间在liveplan的开始结束时间之间的记录

        }else{
//            LiveRecord liveRecord = liveRecordService.getLastRecord(Long.valueOf(requestVo.getStreamName()));
            //开始时间在liveplan时间之后且是直播状态或是开始时间在liveplan的开始结束时间之间的记录
            requestVo.setLivePlanId(0);
        }*/
        //从缓存中获取直播间当前对应的直播计划，如果没有给默认值0
//        LivePlan livePlan = livePlanService.getByStartTime(Integer.valueOf(requestVo.getStreamName()),new Date());
        /*String livePlanId = redisUtil.get(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+requestVo.getStreamName());
        if (!"publish".equals(requestVo.getAction())){
            if (livePlanId==null){
                PublishHistory publishHistory = publishHistoryService.getLastBegin(requestVo.getStreamName());
                if (publishHistory!=null){
                    livePlanId = publishHistory.getLivePlanId()+"";
                }
            }
        }*/
//        requestVo.setLivePlanId(livePlanId==null?0:Integer.valueOf(livePlanId));
        PublishHistory publishHistory = publishHistoryService.addPublish(requestVo);
        if (publishHistory!=null){
            if ("publish".equals(requestVo.getAction())){
                /**
                 * 开始推流
                 * 先检查redis中执行计划是否已存在（存在说明管理后台点击了开始直播）
                 */
                String planId = redisUtil.get(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+requestVo.getLivePlanId());
                if (planId!=null){
                    StreamMessage streamMessage = new StreamMessage(1);
                    chatRoomService.mngSendMessage(Integer.valueOf(requestVo.getLivePlanId()),streamMessage);
                }
//                liveRoomService.updateStatus(requestVo.getStreamName(),1);
//                redisUtil.set(RedisKey.REDIS_KEY_LIVE_STATUS+requestVo.getStreamName(),1);
                /*ChatRoomInfo[] chatroomCreateChatRoomInfo = {new ChatRoomInfo(requestVo.getLivePlanId()+"","" )};
                try {
                    RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.create(chatroomCreateChatRoomInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                }*/
            }else {
                /**
                 * 结束推流
                 */
                String planId = redisUtil.get(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+requestVo.getLivePlanId());
                if (planId!=null){
                    StreamMessage streamMessage = new StreamMessage(0);
                    chatRoomService.mngSendMessage(Integer.valueOf(requestVo.getLivePlanId()),streamMessage);
                }
//                redisUtil.set(RedisKey.REDIS_KEY_LIVE_STATUS+requestVo.getStreamName(),0);
//                liveRoomService.updateStatus(requestVo.getStreamName(),0);
                /*String[] rooms = {requestVo.getStreamName()};
                try {
                    //销毁聊天室
                    RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.destroy(rooms);
                } catch (Exception e) {
                    e.printStackTrace();
                }*/
            }
            return JsonUtil.getSuccessJsonStr("ok",publishHistory);
        }
        return JsonUtil.getFailJsonStr("添加失败");
    }

    @RequestMapping("/getPageList")
    public String getPageList(@RequestBody JSONObject json){
        List<PublishHistory> list = publishHistoryService.getPageList();
        return JsonUtil.getSuccessJsonStr("ok",list);
    }

    /*@RequestMapping("/testBatchInsert")
    public String testBatchInsert(){

        List<LiveOrder> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            LiveOrder liveOrder1 = new LiveOrder();
            liveOrder1.setLivePlanId(1);
            liveOrder1.setOrderDetailId(0l);
            liveOrder1.setOrderInfoId(0l);
            liveOrder1.setOrderObjectId(0l);
            liveOrder1.setLl("11");
            list.add(liveOrder1);
        }
       *//*
        LiveOrder liveOrder2 = new LiveOrder();
        liveOrder2.setLivePlanId(1);
        liveOrder2.setOrderDetailId(0l);
        liveOrder2.setOrderInfoId(0l);
        liveOrder2.setOrderObjectId(0l);
        list.add(liveOrder2);
        LiveOrder liveOrder3 = new LiveOrder();
        liveOrder3.setLivePlanId(1);
        liveOrder3.setOrderDetailId(0l);
        liveOrder3.setOrderInfoId(0l);
        liveOrder3.setOrderObjectId(0l);
        list.add(liveOrder3);*//*
//        liveOrderMapper.batchInsert(list);
        long startTime1 = System.currentTimeMillis();
        liveOrderMapper.batchInsert(list);
        System.out.println(System.currentTimeMillis()-startTime1+"==================多values拼接==========");


        return JsonUtil.getSuccessJsonStr("ok",list);
    }

    @RequestMapping("/testBatchInsert1")
    public String testBatchInsert1(){

        List<LiveOrder> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            LiveOrder liveOrder1 = new LiveOrder();
            liveOrder1.setLivePlanId(1);
            liveOrder1.setOrderDetailId(0l);
            liveOrder1.setOrderInfoId(0l);
            liveOrder1.setOrderObjectId(0l);
            liveOrder1.setLl("11");
            list.add(liveOrder1);
        }
       *//*
        LiveOrder liveOrder2 = new LiveOrder();
        liveOrder2.setLivePlanId(1);
        liveOrder2.setOrderDetailId(0l);
        liveOrder2.setOrderInfoId(0l);
        liveOrder2.setOrderObjectId(0l);
        list.add(liveOrder2);
        LiveOrder liveOrder3 = new LiveOrder();
        liveOrder3.setLivePlanId(1);
        liveOrder3.setOrderDetailId(0l);
        liveOrder3.setOrderInfoId(0l);
        liveOrder3.setOrderObjectId(0l);
        list.add(liveOrder3);*//*
//        liveOrderMapper.batchInsert(list);
        *//*long startTime1 = System.currentTimeMillis();
        liveOrderMapper.batchInsert(list);
        System.out.println(System.currentTimeMillis()-startTime1+"==================多values拼接==========");*//*
        long startTime = System.currentTimeMillis();
        liveOrderMapper.batchInsert1(list);
        System.out.println(System.currentTimeMillis()-startTime+"===================多条sql;处理================");
        return JsonUtil.getSuccessJsonStr("ok",list);
    }*/
}
